<template>
  <el-card title="编辑销售订单">
    <div class="required-note">* 为必填项</div>

    <!-- 订单详情区域 -->
    <el-form
      ref="saleFormRef"
      :model="saleForm"
      :rules="formRules"
      label-width="120px"
      class="order-details-form"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="销售单号" prop="saleId">
            <el-input v-model="saleForm.saleId" placeholder="可不填写,自动生成"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="saleForm.customerName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="saleForm.contactPerson" readonly></el-input>
          </el-form-item>
        </el-col>
       
      </el-row>

      <!-- 客户信息区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="客户编号" prop="customerId">
            <el-input
              v-model="saleForm.customerId"
              @blur="handleCustomerIdBlur"
              placeholder="输入客户编号后自动填充"
            ></el-input>
          </el-form-item>
        </el-col>
         <el-col :span="8">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="saleForm.phone" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input v-model="saleForm.description" type="textarea" :rows="2" placeholder="请输入备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 产品信息区域 -->
    <div class="product-info-section">
      <el-card title="产品信息">
        <div class="product-header">
          <el-button type="primary" @click="addEmptyProduct">+ 新增产品</el-button>
          <span style="margin-left: 10px; color: #666;">产品总数: {{ GetProduct.length }}</span>
        </div>
        
        <!-- 产品选择表格 -->
        <el-table
          ref="productTableRef"
          :data="GetProduct"
          border
          style="width: 100%; margin-top: 20px;"
          @selection-change="handleProductSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="300">
            <template #default="scope">
              {{ scope.row.productName || '暂无数据' }}
            </template>
          </el-table-column>
          <el-table-column prop="productCode" label="产品编码" width="120">
            <template #default="scope">
              {{ scope.row.productCode || '暂无数据' }}
            </template>
          </el-table-column>
          <el-table-column prop="specifications" label="规格" width="120">
            <template #default="scope">
              {{ scope.row.specifications || '暂无数据' }}
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" width="80">
            <template #default="scope">
              {{ scope.row.unitName || '暂无数据' }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120" align="right">
            <template #default="scope">
              {{ scope.row.price  }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 已选产品区域 -->
    <div class="selected-products-section">
      <el-card title="已选产品">
        <el-table
          v-if="selectedProducts.length > 0"
          :data="selectedProducts"
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="300"></el-table-column>
          <el-table-column prop="productCode" label="产品编码" width="120"></el-table-column>
          <el-table-column prop="specifications" label="规格" width="120"></el-table-column>
          <el-table-column prop="unitName" label="单位" width="80"></el-table-column>
          <el-table-column prop="price" label="单价" width="120" >
            <template #default="scope">
              {{ scope.row.price }}
            </template>
          </el-table-column>
           <el-table-column prop="num" label="数量" align="center">
        <template #default="scope">
          <el-input-number
            v-model.number="scope.row.num"
            :min="1"
            :precision="0"
            @change="handleQuantityChange(scope.row)"
            placeholder="输入数量"
          />
        </template>
      </el-table-column>
        <el-table-column prop="total" label="总价" >
        <template #default="scope">
          {{ scope.row.total.toFixed(2) }}
        </template>
      </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                class="delete-btn"
                @click="removeSelectedProduct(scope.row.productId)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="no-products-tip">暂无选中产品</div>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElCard, ElRow, ElCol, ElMessage, ElTable, ElTableColumn, ElSelect, ElOption, ElDatePicker, ElInputNumber } from 'element-plus';
import { Check, Delete } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';
import http from '@/http/axiosHelper';

// 路由相关
const router = useRouter();

// 表单引用
const saleFormRef = ref<FormInstance>();

// 表单数据
const saleForm = reactive({
  "saleId": "",
  "productName": "",
  "updateName": 0,
  "productId": 0,
  "productSpecs": "",
  "unitId": 0,
  "price": 0,
  "num": 0,
  "total": 0,
  "refundNum": 0,
  "customerId": '',
  "customerName": "",
  "contactPerson": "",
  "phone": "",
  "description": "",
  "state": 1,
  "recorded": false,

});

// 产品数据
const productList = ref<any[]>([]);
const selectedProducts = ref<any[]>([]);
const isLoading = ref(false);
const productTableRef = ref<InstanceType<typeof ElTable>>();

// 表单验证规则
const formRules = reactive<FormRules>({
  orderType: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
  customerId: [
    { required: true, message: '请输入客户编号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '客户编号必须为数字', trigger: 'blur' }
  ],
  deliveryDate: [{ required: true, message: '请选择发货日期', trigger: 'change' }]
});
import Purchase from '@/http/PurSale';
// 处理客户编号失焦事件
const handleCustomerIdBlur = async () => {
  if (!saleForm.customerId) return;

  try {
    const response = await http.get(`/scmreadconsul/api/Sale/GetClient`, {
      params: { ClientId: saleForm.customerId }
    });
    
    if (response.data.code === 200 && response.data.datas && response.data.datas.length > 0) {
      const clientData = response.data.datas[0];
      saleForm.customerName = clientData.clientName;
      saleForm.contactPerson = clientData.clientContact;
      saleForm.phone = clientData.clientTel;
    } else {
      ElMessage.warning('未找到该客户信息');
      // 清空客户信息
      saleForm.customerName = '';
      saleForm.contactPerson = '';
      saleForm.phone = '';
    }
  } catch (error) {
    ElMessage.error('获取客户信息失败');
    console.error('获取客户信息错误:', error);
    // 清空客户信息
    saleForm.customerName = '';
    saleForm.contactPerson = '';
    saleForm.phone = '';
  }
};

// 处理数量变化
const handleQuantityChange = (product: any) => {
  // 确保单价和数量都是数字
  const price = Number(product.price) || 0;
  const quantity = Number(product.num) || 0;
  // 计算总价并绑定到采购单的total字段
  product.total = price * quantity;
};
const GetProduct = ref([])
// 获取产品列表
const fetchProductList = async () => {
  try {
 
    const response = await http.get('/scmreadconsul/api/Sale/GetSaleProduct');
    console.log('API响应:', response.data);
    
    if (response.data.code === 200) {
      GetProduct.value = response.data.datas || [];
      console.log('产品列表数据:', GetProduct.value);
      ElMessage.success('产品列表获取成功');
    } else {
      ElMessage.warning('获取产品列表失败: ' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取产品列表时发生错误');
    console.error('获取产品列表错误:', error);
  }
};

// 处理产品选择变化
const handleProductSelectionChange = (selection: any[]) => {
  // 过滤掉已选中的产品
  const newProducts = selection
    .filter(item => !selectedProducts.value.some(p => p.productId === item.productId))
    .map(item => ({
      productId: item.productId,
      productName: item.productName,
      productCode: item.productCode,
      productSpecs: item.specifications,
      unitId: item.unitId,
      unitName: item.unitName,
      price: item.price,
      num: 1,
      total: item.price * 1
    }));

       if (selection.length > 0) {
    const firstProduct = selection[0];
    saleForm.productName = firstProduct.productName;
    saleForm.productId = firstProduct.productId;
    saleForm.productSpecs = firstProduct.specifications; // 注意字段名是否匹配
    saleForm.unitId = firstProduct.unitId; // 需确认产品表格里的“单位ID”字段名
    saleForm.price = firstProduct.price;
    saleForm.num = 1; // 或从 newProducts 里取 quantity
    saleForm.total = firstProduct.price * 1; // 或直接用 firstProduct.totalPrice
  }

  // 添加新选中的产品
  selectedProducts.value = [...selectedProducts.value, ...newProducts];

  // 清除表格选中状态
  if (productTableRef.value) {
    productTableRef.value.clearSelection();
  }
};

// 添加空产品行
const addEmptyProduct = () => {
  selectedProducts.value.push({
    productName: '',
    productCode: '',
    productSpecs: '',
    unitName: '',
    price: 0,
    num: 1,
    total: 0,
    productId: 0,
    unitId: 0
  });
};

// 移除选中的产品
const removeSelectedProduct = (productId: number) => {
  selectedProducts.value = selectedProducts.value.filter(p => p.productId !== productId);
};

// 提交表单
const submitForm = async () => {
  if (!saleFormRef.value) return;

  try {
    await saleFormRef.value.validate();

    if (selectedProducts.value.length === 0) {
      ElMessage.warning('请至少添加一个产品');
      return;
    }

    // 构建提交数据
const submitData = {
  ...saleForm,
  productDetails: selectedProducts.value.map(product => ({
    product_id: product.productId,
    product_name: product.productName,
    product_code: product.productCode,
    ProductSpecs: product.productSpecs, // 修改字段名为ProductSpecs以匹配数据库
    unit_id: product.unitId,
    unit_name: product.unitName,
    price: product.price,
    num: product.num,
    total: product.total
  }))
};

    // 调用API提交销售订单
    const response = await http.post('/scmwriteconsul/api/Sale/AddSale', submitData);
    
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '销售订单添加成功');
      // 返回列表页面
      router.push('/showSale');
    } else {
      ElMessage.error(response.data.msg || '添加失败');
    }
  } catch (error) {
    console.error('提交表单失败:', error);
    ElMessage.error('提交失败，请重试');
  }
};

// 重置表单
const resetForm = () => {
  if (saleFormRef.value) {
    saleFormRef.value.resetFields();
  }
  selectedProducts.value = [];
  
  // 重置默认值
 
  saleForm.state = 1;
  saleForm.recorded = false;

  saleForm.updateName = 1;
};

// 页面加载时初始化
onMounted(() => {
    fetchProductList();
  
});



// 获取采购单详情
const fetchPurchaseDetail = async (id: number) => {
  try {
    // 使用 axios 直接调用，因为 Read store 的 baseURL 不正确
    const response = await http.get('/scmreadconsul/api/Sale/FanSale', {
      params: { Id: id }
    });
    
    if (response.data.code === 200 && response.data.data) {
      const data = response.data.data;
      
      // 回显表单数据
      Object.assign(saleForm, {
        id: data.id,
        saleId: data.saleId,
        productName: data.productName,
        productId: data.productId,
        productSpecs: data.productSpecs,
        unitId: data.unitId,
        price: data.price,
        num: data.num,
        total: data.total,
        refundNum: data.refundNum,
        customerId: data.customerId,
        customerName: data.customerName,
        contactPerson: data.contactPerson,
        phone: data.phone,
        description: data.description,
        state: data.state,
        recorded: data.recorded,
      });

      // 将当前产品添加到已选产品列表
      selectedProducts.value = [{
        productId: data.productId,
        productCode: data.productId, // 如果没有productCode字段，使用productId
        productName: data.productName,
        specifications: data.productSpecs,
        unitId: data.unitId,
        price: data.price,
        num: data.num,
        total: data.total
      }];
    } else {
      ElMessage.error('获取采购单详情失败');
    }
  } catch (error) {
    ElMessage.error('获取采购单详情时发生错误');
    console.error('获取采购单详情错误:', error);
  }
};
import { useRoute } from 'vue-router';
const route=useRoute();
// 页面加载时获取产品列表和数据回显
onMounted(async () => {
  await fetchProductList();
  
  // 检查是否有ID参数，如果有则获取详情
  const id = route.query.id;
  if (id) {
    await fetchPurchaseDetail(Number(id));
  }
});
</script>

<style scoped>
.required-note {
  color: #ff4d4f;
  margin-bottom: 16px;
  text-align: right;
}

.order-details-form {
  margin-bottom: 20px;
}

.product-info-section,
.selected-products-section {
  margin-bottom: 20px;
}

.no-products-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.product-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.delete-btn {
  color: #ff4d4f;
}

::v-deep .el-table__header-wrapper th {
  background-color: #f5f7fa;
  font-weight: 500;
}
</style>
